package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.*;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.huaweicloud.sdk.iotda.v5.IoTDAClient;
import com.huaweicloud.sdk.iotda.v5.model.*;
import com.zzyl.common.core.domain.AjaxResult;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.common.utils.uuid.UUID;
import com.zzyl.nursing.dto.DeviceDto;
import com.zzyl.nursing.vo.DeviceDetailVo;
import com.zzyl.nursing.vo.ProductVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.service.IDeviceService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

/**
 * 设备管理Service业务层处理
 * 
 * @author zhaoyiyang
 * @date 2025-08-01
 */
@Service
public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> implements IDeviceService {
    @Autowired
    private DeviceMapper deviceMapper;

    /**
     * 查询设备管理
     *
     * @param id 设备管理主键
     * @return 设备管理
     */
    @Override
    public Device selectDeviceById(Long id) {
        return getById(id);
    }

    /**
     * 查询设备管理列表
     *
     * @param device 设备管理
     * @return 设备管理
     */
    @Override
    public List<Device> selectDeviceList(Device device) {
        return deviceMapper.selectDeviceList(device);
    }



    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private IoTDAClient client;

    public static final String IOT_ALL_PRODUCT_LIST = "iot:all_product_list";

    /**
     * 同步产品列表
     */
    @Override
    public void syncProductList() {
        // 请求参数
        ListProductsRequest listProductsRequest = new ListProductsRequest();
        // 设置条数
        listProductsRequest.setLimit(50);
        // 发起请求
        ListProductsResponse response = client.listProducts(listProductsRequest);
        if (response.getHttpStatusCode() != 200) {
            throw new BaseException("物联网接口 - 查询产品，同步失败");
        }
        // 存储到redis
        redisTemplate.opsForValue().set(IOT_ALL_PRODUCT_LIST, JSONUtil.toJsonStr(response.getProducts()));

    }


    /**
     * 查询所有产品列表
     *
     * @return
     */
    @Override
    public List<ProductVo> allProduct() {
        // 从redis中查询数据
        String jsonStr = redisTemplate.opsForValue().get(IOT_ALL_PRODUCT_LIST);
        // 如果数据为空，则返回一个空集合
        if (StringUtils.isEmpty(jsonStr)) {
            return Collections.emptyList();
        }
        // 解析数据，并返回
        return JSONUtil.toList(jsonStr, ProductVo.class);
    }
    @Transactional
    @Override
    public void registerDevice(DeviceDto deviceDto) {
//        1.设备名称是否重复
        long count = this.count(Wrappers.<Device>lambdaQuery().eq(Device::getDeviceName, deviceDto.getDeviceName()));
        if (count > 0) {
            throw new BaseException("设备名称重复");
        }
//        2.设备标识码是否重复
        count = this.count(Wrappers.<Device>lambdaQuery().eq(Device::getNodeId, deviceDto.getNodeId()));
        if (count > 0) {
            throw new BaseException("设备标识码重复");
        }
//        3.同一位置是否绑定了相同的设备
        count = this.count(Wrappers.<Device>lambdaQuery()
                .eq(Device::getProductKey, deviceDto.getProductKey())
                .eq(Device::getBindingLocation, deviceDto.getBindingLocation())
                .eq(Device::getLocationType, deviceDto.getLocationType())
                .eq(deviceDto.getPhysicalLocationType() != null,
                        Device::getPhysicalLocationType, deviceDto.getPhysicalLocationType())

        );
        if (count > 0) {
            throw new BaseException("已绑定过设备!");
        }
//        4.注册设备华为-IOT
        AddDevice body = new AddDevice();
        AddDeviceRequest request = new AddDeviceRequest();
        body.setDeviceName(deviceDto.getDeviceName());
        body.setNodeId(deviceDto.getNodeId());
        body.setProductId(deviceDto.getProductKey());

        AuthInfo authInfo = new AuthInfo();
        String secret = UUID.randomUUID().toString().replaceAll("-", "");
        authInfo.setSecret(secret);
        body.setAuthInfo(authInfo);
        request.setBody(body);

        AddDeviceResponse addDeviceResponse = client.addDevice(request);
        if (addDeviceResponse.getHttpStatusCode() != 201) {
            throw new RuntimeException("物联网接口 - 注册设备，调用失败");
        }


//        5.本地保存设备信息
        Device device = BeanUtil.toBean(deviceDto, Device.class);
        device.setDeviceName(addDeviceResponse.getDeviceName());

        // 秘钥
        device.setSecret(secret);
        // 设备id、设备绑定状态
        device.setIotId(addDeviceResponse.getDeviceId());
        save(device);
    }

    @Override
    public DeviceDetailVo queryDeviceDetail(String iotId) {
//        首先查询本地数据库,若本地数据库没有,则IOT平台也不会有
        Device device = this.getOne(Wrappers.<Device>lambdaQuery().eq(Device::getIotId, iotId));
        if (ObjectUtils.isEmpty(device)) {
            new BaseException("设备不存在");
        }
//        确认本地数据库存在对应设备,则开始调用华为云接口查询IOT平台信息
//        先开始构造请求参数
        ShowDeviceRequest request = new ShowDeviceRequest();
//        将设备ID设置到请求参数中
        request.setDeviceId(iotId);
        ShowDeviceResponse response = client.showDevice(request);
        if (ObjectUtils.isEmpty(response)) {
            new BaseException("物联网接口查询设备信息失败");
        }
//        创建对象,构建IOT平台所需要的对象
        DeviceDetailVo detailVo = BeanUtil.toBean(device, DeviceDetailVo.class);
        detailVo.setDeviceStatus(response.getStatus());
        String activeTimeStr = response.getActiveTime();
//        日期转换,参考官方文档
        if (StrUtil.isNotEmpty(activeTimeStr)) {
//            进行日期转换,这里转换的格式是：yyyy-MM-dd'T'HH:mm:ss.SSSZ
            LocalDateTime activeTime = LocalDateTimeUtil.parse(activeTimeStr, DatePattern.UTC_MS_PATTERN);
            detailVo.setActiveTime(activeTime);
        }
        return detailVo;

    }

    @Override
    public AjaxResult queryServiceProperties(String iotId) {
        ShowDeviceShadowRequest request = new ShowDeviceShadowRequest();
        request.setDeviceId(iotId);
        ShowDeviceShadowResponse response = client.showDeviceShadow(request);
        if (response.getHttpStatusCode() != 200) {
            throw new RuntimeException("查询设备影子失败");
        }
        List<DeviceShadowData> shadow = response.getShadow();
        if (CollUtil.isEmpty(shadow)) {
//            若数据为空
//            throw new RuntimeException("设备影子无数据!");
            List<Object> empty = CollUtil.empty(shadow.getClass());
            return AjaxResult.success(empty);
        }
//        数据不为空则获取其中数据
        DeviceShadowProperties reported = shadow.get(0).getReported();
//        这里的Json对象实际上是map对象,这样的转换可以更方便我们进行取值
        JSONObject jsonObject = JSONUtil.parseObj(reported.getProperties());
        List<Object> list = new ArrayList<>();
        String eventTimeStr = reported.getEventTime();
        LocalDateTime eventTime = DateUtil.parseLocalDateTime(eventTimeStr, "yyyyMMdd'T'HHmmss'Z'");
//        转换时区到东八区
        eventTime = eventTime.atZone(ZoneId.of("Asia/Shanghai")).toLocalDateTime();
        LocalDateTime finalEventTime = eventTime;
        jsonObject.forEach((key, value) -> {
            Map<String, Object> map = new HashMap<>();
            map.put("functionId", key);
            map.put("value", value);
            map.put("eventTime", finalEventTime);
            list.add(map);
                }
        );
        return AjaxResult.success(list);
    }
    @Transactional
    @Override
    public AjaxResult updateDeviceProperties(DeviceDto deviceDto) {
//        TODO:这里的修改逻辑有着一定的问题,如果我们把固定位置的设备修改为随身设备,就会导致随身设备存在固定设备的位置类型以及位置备注

        /*
        按逻辑上来说,我们应该先修改本地的,如果本地的修改成功,再尝试修改云端数据
        这样可以保证如果我们在修改问题中出错,可以先回滚本地数据库,同时还不会
        影响云端数据
*/
//        获取设备ID
        String iotId = this.getOne(Wrappers.<Device>lambdaQuery().eq(Device::getId, deviceDto.getId())).getIotId();
//        新建一个修改设备请求
        UpdateDeviceRequest request = new UpdateDeviceRequest();
//        新建一个修改设备的请求体
        UpdateDevice body = new UpdateDevice();
//        设置修改后的设备名称和描述
        body.setDeviceName(deviceDto.getDeviceName());
        body.setDescription(deviceDto.getDeviceDescription());
//        构建认证信息
        AuthInfoWithoutSecret autoInfo = new AuthInfoWithoutSecret();
//        设置为安全接入
        autoInfo.setSecureAccess(true);
        body.setAuthInfo(autoInfo);
//        将请求体放到请求中
        request.setBody(body);
//        将设备ID设置到请求中
        request.setDeviceId(iotId);
/*
        先修改本地数据库中的数据
        TODO:其实这里我在想要不要优化,因为其实我们的编辑操作总共也就是名字,绑定位置,绑定类型三个字段,所以其实这里可以不用复制整个Bean两个set就可以了
*/
        Device device = BeanUtil.toBean(deviceDto, Device.class);
        device.setBindingLocation(deviceDto.getBindingLocation().toString());
        this.updateById(device);
//        发送请求到IOT平台修改平台的设备信息
        UpdateDeviceResponse response = client.updateDevice(request);
        if (response.getHttpStatusCode()!=200) {
            throw new RuntimeException("修改设备信息失败");
        }
        return AjaxResult.success();
    }

    @Transactional
    @Override
    public AjaxResult deleteDevice(String iotId) {
        DeleteDeviceRequest request = new DeleteDeviceRequest();
        request.setDeviceId(iotId);
//        先删除本地数据库
        try {
            this.remove(Wrappers.<Device>lambdaQuery().eq(Device::getIotId, iotId));
        } catch (Exception e) {
            throw new BaseException("本地删除失败");
        }
        DeleteDeviceResponse response = client.deleteDevice(request);
        if (response.getHttpStatusCode()!=204) {
            throw new BaseException("IOT平台删除设备失败");
        }
        return AjaxResult.success();
    }

    /**
     * 查询产品详情
     * @param productKey
     * @return
     */
    @Override
    public AjaxResult queryProduct(String productKey) {
        // 参数校验
        if(StringUtils.isEmpty(productKey)) {
            throw new BaseException("请输入正确的参数");
        }
        // 调用华为云IOT平台接口
        ShowProductRequest showProductRequest = new ShowProductRequest();
        showProductRequest.setProductId(productKey);
        ShowProductResponse response;

        try {
            response = client.showProduct(showProductRequest);
        } catch (Exception e) {
            throw new BaseException("查询产品详情失败");
        }
        // 判断是否存在服务数据
        List<ServiceCapability> serviceCapabilities = response.getServiceCapabilities();
        if(CollUtil.isEmpty(serviceCapabilities)) {
            return AjaxResult.success(Collections.emptyList());
        }

        return AjaxResult.success(serviceCapabilities);
    }
}
